package com.link_with_health.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;


import com.auth0.jwt.interfaces.Header;
import com.auth0.jwt.interfaces.Payload;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.StringUtils;
import org.apache.commons.collections4.map.HashedMap;

import java.util.Date;
import java.util.Map;
import java.util.Calendar;
import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;

public class JWTUtil {
    private static String SECRET = "tokenByLWH";

    /**
     * 生成Token
     * @param map //传入payload 载荷
     * @return 返回token
     */
    public static String createToken(Map<String, String> map){
        JWTCreator.Builder builder = JWT.create();
        map.forEach((k,v)-> {
            builder.withClaim(k,v);
        });
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE,2);//两天内
        builder.withExpiresAt(instance.getTime());
        return builder.sign(Algorithm.HMAC256(SECRET));

    }

    /**
     * 验证token
     * @param token token
     */
    public static void verify(String token){
        JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
    }

    /**
     * 获取JWT对象
     * @param token 验签
     * @return 返回
     */
    public static DecodedJWT getJWT(String token){
        return JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
    }

    /**
     * 获取JWT中的header
     * @param token 验签
     * @return 返回 header json格式
     */
    public static String getHeader(String token){
        return StringUtils.newStringUtf8(Base64.decodeBase64(getJWT(token).getHeader()));
    }

    /**
     * 获取JWT中的playload
     * @param token 验签
     * @return 返回playload json格式
     */
    public static String  getPlayload(String token){
        return StringUtils.newStringUtf8(Base64.decodeBase64(getJWT(token).getPayload()));
    }



    public static void main(String[] args) {
        HashMap<String,String> playload = new HashMap<>();
        playload.put("test","aaa");

        String asd = JWTUtil.createToken(new HashedMap<>());
        System.out.println(asd);
        String as = JWTUtil.getJWT(asd).getHeader();
        as = StringUtils.newStringUtf8(Base64.decodeBase64(as));
        System.out.println(as);

        String load = StringUtils.newStringUtf8(Base64.decodeBase64(JWTUtil.getJWT(asd).getPayload()));
        System.out.println(load);


        //System.out.printf("%s %s %s", as, load ,signature);

    }

}
